package cn.iocoder.yudao.module.crm.service.importtask;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.crm.controller.admin.clue.vo.CrmClueImportReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.clue.vo.CrmClueImportRespVO;
import cn.iocoder.yudao.module.crm.controller.admin.customer.vo.customer.CrmCustomerImportReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.customer.vo.customer.CrmCustomerImportRespVO;
import cn.iocoder.yudao.module.crm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.crm.mq.producer.ImportTaskProducer;
import cn.iocoder.yudao.module.crm.service.clue.CrmClueService;
import cn.iocoder.yudao.module.crm.service.customFieldHead.CustomFieldHeadService;
import cn.iocoder.yudao.module.crm.service.customer.CrmCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;

import cn.iocoder.yudao.module.crm.controller.admin.importtask.vo.*;
import cn.iocoder.yudao.module.crm.dal.dataobject.importtask.ImportTaskDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.crm.dal.mysql.importtask.ImportTaskMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 导入任务 Service 实现类
 *
 * @author 数创万维
 */
@Slf4j
@Service
@Validated
public class ImportTaskServiceImpl implements ImportTaskService {

    @Resource
    private ImportTaskMapper importTaskMapper;

    @Resource
    private CrmClueService crmClueService;

    @Resource
    private CrmCustomerService crmCustomerService;

    @Resource
    private ImportTaskProducer importTaskProducer;

    @Resource
    private CustomFieldHeadService customFieldHeadService;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Long createImportTask(ImportTaskSaveReqVO createReqVO) {
        // 插入
        ImportTaskDO importTask = BeanUtils.toBean(createReqVO, ImportTaskDO.class);
        importTaskMapper.insert(importTask);

        importTaskProducer. sendImportTaskMessage(TenantContextHolder.getTenantId(), importTask.getId());
        // 返回
        return importTask.getId();
    }

    @Override
    public void updateImportTask(ImportTaskSaveReqVO updateReqVO) {
        // 更新
        ImportTaskDO updateObj = BeanUtils.toBean(updateReqVO, ImportTaskDO.class);
        importTaskMapper.updateById(updateObj);
    }

    @Override
    @Async
    public void updateImportTaskAsync(ImportTaskSaveReqVO updateReqVO) {
        // 更新
        ImportTaskDO updateObj = BeanUtils.toBean(updateReqVO, ImportTaskDO.class);
        importTaskMapper.updateById(updateObj);
    }

    @Override
    public ImportTaskDO getRunningTask() {
        return importTaskMapper.selectOne(ImportTaskDO::getStatus, 1);
    }

    @Override
    public ImportTaskDO getRunnableTask() {
        return importTaskMapper.selectOne(
                new LambdaQueryWrapperX<ImportTaskDO>()
                        .eq(ImportTaskDO::getStatus, 0)
                        .orderByAsc(ImportTaskDO::getCreateTime)
                        .last("limit 1")
        );
    }

    @Override
    public void deleteImportTask(Long id) {
        // 删除
        importTaskMapper.deleteById(id);
    }


    @Override
    public ImportTaskDO getImportTask(Long id) {
        return importTaskMapper.selectById(id);
    }

    @Override
    public PageResult<ImportTaskDO> getImportTaskPage(ImportTaskPageReqVO pageReqVO) {
        return importTaskMapper.selectPage(pageReqVO);
    }

    @Override
    public void executeByMq(Long taskId) {
        ImportTaskDO importTask = getImportTask(taskId);
        executeTask(importTask);
    }

    @Override
    public void executeTask(ImportTaskDO runnableTask) {
        if (Objects.equals(runnableTask.getBizType(), CrmBizTypeEnum.CRM_CLUE.getType())) {
            CrmClueImportReqVO importReqVO = CrmClueImportReqVO.builder()
                    .moduleId(runnableTask.getModuleId())
                    .pool(runnableTask.getPool() == 1)
                    .ownerUserId(runnableTask.getOwnerUserId())
                    .filepath(runnableTask.getFilePath())
                    .repeatHandleType(runnableTask.getRepeatHandle())
                    .repeatHandleField(runnableTask.getRepeatField())
                    .tenantId(runnableTask.getTenantId())
                    .build();
            try {
//                List<CrmClueImportExcelVO> list = ExcelUtils.read0(importReqVO.getFilepath(), CrmClueImportExcelVO.class);
//                LeadsUploadService leadsUploadService = new LeadsUploadService();
//                leadsUploadService.importExcel(importReqVO.getFilepath(),runnableTask.getModuleId(),importReqVO.getRepeatHandleField(),importReqVO.getRepeatHandleType());
//                List<CrmClueImportExcelVO> list  =leadsUploadService.getClueImportExcelVOS();
//                ImportTaskSaveReqVO save = new ImportTaskSaveReqVO();
//                save.setId(runnableTask.getId());
//                save.setStatus(1);
//                save.setDataCount(list.size());
//                updateImportTask(save);

//                CrmClueImportRespVO crmClueImportRespVO = crmClueService.importClueList(list, importReqVO);
                CrmClueImportRespVO crmClueImportRespVO = crmClueService.customImportClueList(null, importReqVO,runnableTask.getId());
                ImportTaskSaveReqVO save = new ImportTaskSaveReqVO();
                save.setId(runnableTask.getId());
                save.setFinishTime(LocalDateTime.now());
                if (StringUtils.isNotEmpty(crmClueImportRespVO.getErrorFileUrl())) {
                    save.setStatus(3);
                } else {
                    save.setStatus(2);
                }
                save.setInsertCount(crmClueImportRespVO.getAddCount());
                save.setUpdateCount(crmClueImportRespVO.getUpdateCount());
                save.setDataCount(crmClueImportRespVO.getDataCount());
                save.setErrorFileUrl(crmClueImportRespVO.getErrorFileUrl());
                updateImportTask(save);
                redisTemplate.delete("import_task:" + runnableTask.getId());
            } catch (Exception e) {
                ImportTaskSaveReqVO save = new ImportTaskSaveReqVO();
                save.setId(runnableTask.getId());
                save.setStatus(3); // 失败
                save.setErrorMsg(e.getMessage());
                updateImportTask(save);
                throw exception(new ErrorCode(100500, "任务执行失败"));
            }
        } else if (Objects.equals(runnableTask.getBizType(), CrmBizTypeEnum.CRM_CUSTOMER.getType())) {
            CrmCustomerImportReqVO importReqVO = CrmCustomerImportReqVO.builder()
                    .moduleId(runnableTask.getModuleId())
                    .pool(runnableTask.getPool() == 1)
                    .ownerUserId(runnableTask.getOwnerUserId())
                    .filepath(runnableTask.getFilePath())
                    .repeatHandleType(runnableTask.getRepeatHandle())
                    .repeatHandleField(runnableTask.getRepeatField())
                    .build();

            try {
//                List<CrmCustomerImportExcelVO> list = ExcelUtils.read0(importReqVO.getFilepath(), CrmCustomerImportExcelVO.class);
//                CrmCustomerImportRespVO crmCustomerImportRespVO = crmCustomerService.customImportCustomerList(null, importReqVO);
                CrmCustomerImportRespVO crmCustomerImportRespVO = crmCustomerService.customImportCustomerList(null, importReqVO,runnableTask.getId());
                ImportTaskSaveReqVO save = new ImportTaskSaveReqVO();
                save.setId(runnableTask.getId());
                save.setFinishTime(LocalDateTime.now());
                if (StringUtils.isNotEmpty(crmCustomerImportRespVO.getErrorFileUrl())) {
                    save.setStatus(3);
                } else {
                    save.setStatus(2);
                }
                save.setInsertCount(crmCustomerImportRespVO.getAddCount());
                save.setUpdateCount(crmCustomerImportRespVO.getUpdateCount());
                save.setDataCount(crmCustomerImportRespVO.getDataCount());
                save.setErrorFileUrl(crmCustomerImportRespVO.getErrorFileUrl());
                updateImportTask(save);
                redisTemplate.delete("import_task:" + runnableTask.getId());
            } catch (Exception e) {
                ImportTaskSaveReqVO save = new ImportTaskSaveReqVO();
                save.setId(runnableTask.getId());
                save.setStatus(3); // 失败
                save.setErrorMsg(e.getMessage());
                updateImportTask(save);
                throw exception(new ErrorCode(100500, "任务执行失败"));
            }

        }

    }
}